package com.cqfae.deploycentral.app.services.impl;

import com.cqfae.deploycentral.api.utils.IdGenerator;
import com.cqfae.deploycentral.app.base.BaseConstantCode;
import com.cqfae.deploycentral.app.base.BaseConstants;
import com.cqfae.deploycentral.app.dao.entity.FileSync;
import com.cqfae.deploycentral.app.dao.entity.FileSyncDetail;
import com.cqfae.deploycentral.app.dao.mapper.FileSyncDetailMapper;
import com.cqfae.deploycentral.app.dao.mapper.FileSyncMapper;
import com.cqfae.deploycentral.app.services.FileSyncDetailService;
import com.cqfae.deploycentral.app.utils.NullUtil;
import com.cqfae.deploycentral.app.web.request.FileSyncRequest;
import com.cqfae.deploycentral.app.web.vo.FileSyncDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by JIANGLU009 on 2017/11/6.
 */
@Service
@Transactional
public class FileSyncDetailServiceImpl implements FileSyncDetailService {

    private static Logger logger = LoggerFactory.getLogger(FileSyncDetailServiceImpl.class);

    // 获取ID
    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private FileSyncDetailMapper fileSyncDetailMapper;

    @Autowired
    private FileSyncMapper fileSyncMapper;


    /**
     * 新增
     *
     * @param fileSyncDetail
     * @return
     */
    @Override
    public Integer add(FileSyncDetail fileSyncDetail) {
        Integer num = 0;
        if (fileSyncDetail != null) {
            // 验证编码
            codeCheck(fileSyncDetail);
            // 对string类型的属性做trim
            trimStr(fileSyncDetail);
            // 设置新增ID
            fileSyncDetail.setId(idGenerator.nextId());
            // 设置新增操作者和时间
            fileSyncDetail.setCreateBy("123");
            fileSyncDetail.setCreateTime(new Date());
            // 设置更新操作者和时间
            fileSyncDetail.setUpdateBy("123");
            fileSyncDetail.setUpdateTime(new Date());
            num = fileSyncDetailMapper.insert(fileSyncDetail);
        }
        return num;
    }

    /**
     * 链表查询
     *
     * @param request
     * @return
     */
    @Override
    public List<FileSyncDetailVo> list(FileSyncRequest request) {
        // 项目ID不能为空
        Assert.isTrue(request.getId() != null, "文件同步ID为空");
        // 查询详情
        FileSyncDetail fileSyncDetail = new FileSyncDetail();
        fileSyncDetail.setFileSyncId(request.getId());
        List<FileSyncDetail> fileSyncDetailList = fileSyncDetailMapper.select(fileSyncDetail);
        List<FileSyncDetailVo> fileSyncDetailVoList = new ArrayList<>();
        if (fileSyncDetailList != null && !fileSyncDetailList.isEmpty()) {
            // 将code转换成string
            for (FileSyncDetail fileSyncDetail1 : fileSyncDetailList) {
                FileSyncDetailVo fileSyncDetailVo = new FileSyncDetailVo(fileSyncDetail1);
                codeCheck(fileSyncDetail1);
                fileSyncDetailVo.setStatusCodeStr(BaseConstants.getConstantsCodeMap().get(fileSyncDetail1.getStatus()));
                fileSyncDetailVoList.add(fileSyncDetailVo);
            }
        }
        return fileSyncDetailVoList;
    }

    /**
     * 文件同步回调
     *
     * @param fileSyncDetailVo
     * @return
     */
    @Override
    public Integer detailCallBack(FileSyncDetailVo fileSyncDetailVo) {
        Integer num = 0;
        if (fileSyncDetailVo != null) {
            // 查询处于同步中的文件
            Example example = new Example(FileSync.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("areaCode", fileSyncDetailVo.getArea());
            criteria.andEqualTo("interiorAreaCode", fileSyncDetailVo.getZone());
            criteria.andEqualTo("syncStatus", BaseConstantCode.FILE_SYNC_TYPE_EXECUT_CODE);
            List<FileSync> fileSyncList = fileSyncMapper.selectByExample(example);
            if (fileSyncList != null && !fileSyncList.isEmpty()) {
                for (FileSync fileSync : fileSyncList) {
                    // 更新状态
                    fileSync.setUpdateBy("123");
                    fileSync.setUpdateTime(new Date());
                    fileSync.setSyncStatus(fileSyncDetailVo.getStatus());
                    fileSyncMapper.updateByPrimaryKeySelective(fileSync);
                    // 添加详情
                    FileSyncDetail fileSyncDetail = new FileSyncDetail();
                    fileSyncDetail.setFileSyncId(fileSync.getId());
                    fileSyncDetail.setTargetArea(BaseConstants.getConstantsCodeMap().get(fileSyncDetailVo.getZone()));
                    fileSyncDetail.setSyncTime(fileSyncDetailVo.getTime());
                    fileSyncDetail.setTargetIp(fileSyncDetailVo.getTargetIp());
                    fileSyncDetail.setTargetContent(fileSyncDetailVo.getTargetContent());
                    fileSyncDetail.setStatus(fileSyncDetailVo.getStatus());
                    num += add(fileSyncDetail);
                }
            }
        }
        return num;
    }

    /**
     * 对string类型的属性做trim
     *
     * @param object
     * @return
     */
    private Object trimStr(Object object) {
        if (object != null) {
            Class<?> clz = object.getClass();
            Field[] fields = clz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    if (null != field.get(object) && field.get(object) instanceof String) {
                        String val = String.valueOf(field.get(object));
                        val = val.trim();
                        field.set(object, val);
                    }
                } catch (Exception e) {
                    logger.error("FileSyncDetailServiceImpl.trimStr IllegalAccessException", e);
                }
            }
        }
        return object;
    }

    /**
     * 验证编码
     *
     * @param object
     */
    private void codeCheck(Object object) {
        if (object instanceof FileSyncDetail) {
            FileSyncDetail fileSyncDetail = (FileSyncDetail) object;
            Assert.isTrue(NullUtil.isNotEmpty(BaseConstants.getConstantsCodeMap().get(fileSyncDetail.getStatus())),
                    "此同步状态编码不存在：" + fileSyncDetail.getStatus());
        }
    }

    /**
     * 批量删除详情
     *
     * @param fileSyncId
     * @return
     */
    @Override
    public Integer deleteByFileSyncId(String fileSyncId) {
        int num = 0;
        if (StringUtils.isNotBlank(fileSyncId)) {
            Example example = new Example(FileSyncDetail.class);
            example.createCriteria().andEqualTo("fileSyncId", fileSyncId);
            num = fileSyncDetailMapper.deleteByExample(example);

        }
        return num;
    }

}
